package com.adminsystem.common.aop;


import com.adminsystem.common.utils.JWTUtil;
import com.adminsystem.entity.SysLog;
import com.adminsystem.entity.SysUser;
import com.adminsystem.service.SysLogService;
import com.adminsystem.service.SysUserService;
import com.system.core.http.R;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.Objects;
import java.util.logging.Logger;

@Component
@Aspect
public class SysLogAspect {

    private Logger logger= Logger.getLogger(SysLogAspect.class.getName());
    @Autowired
    private SysLogService sysLogService;

    @Autowired
    private SysUserService sysUserService;

    @Around("@annotation(autoLog)")
    public Object doAround(ProceedingJoinPoint joinPoint, AutoLog autoLog) throws Throwable {
        //操作内容
        String content = autoLog.value();
        //当前时间
//        String createTime = DateUtil.now();
        //当前操作人
        String userName= JWTUtil.getCurrentUserName();
        logger.info("userName:"+userName);

        SysUser sysUser=sysUserService.getByUserName(userName);
        logger.info(sysUser.toString());
        //当前操作人IP
        HttpServletRequest request = ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
        String ip=request.getRemoteAddr();
        SysLog sysLog=new SysLog();
        sysLog.setContent(content);
        sysLog.setUsername(userName);
        sysLog.setCreateTime(new Date());
        sysLog.setIp(ip);
        sysLogService.save(sysLog);
        return (R)joinPoint.proceed();
    }
}
